package com.yy.device.api.web;

import cn.hutool.core.exceptions.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Consumer;


@Slf4j
public final class APIModelHandler {
    private APIModelHandler() {
    }

    public static APIModel execute(Consumer<APIModel> f) {
        APIModel model = APIModel.builder()
                .code(APIResult.OK.getCode())
                .msg(APIResult.OK.getMsg())
                .build();

        try {
            f.accept(model);
        } catch (APIException e) {
            model.setCode(e.getCode());
            model.setMsg(e.getMsg());
            // 拼接i18n错误参数
            if (e.getArgs() != null && e.getArgs().length > 0) {
                StringBuilder sb = new StringBuilder(e.getMsg());
                for (Object arg : e.getArgs()) {
                    sb.append(",").append(arg);
                }
                model.setMsg(sb.toString());
            }
            log.error(ExceptionUtil.stacktraceToString(e));
        } catch (Exception e) {
            model.set(APIResult.ERROR.getCode(), ExceptionUtil.getMessage(e), null);
            log.error(ExceptionUtil.stacktraceToString(e));
        }

        return model;
    }


}
